<template>
  <el-form
    ref="loginForm"
    :model="form"
    :rules="rules"
    label-width="0"
    size="large"
  >
    <el-form-item prop="phone">
      <el-input
        v-model="form.phone"
        prefix-icon="el-icon-iphone"
        clearable
        :placeholder="t('login.mobilePlaceholder')"
      >
        <template #prepend>+86</template>
      </el-input>
    </el-form-item>
    <el-form-item prop="yzm" style="margin-bottom: 35px">
      <div class="login-msg-yzm">
        <el-input
          v-model="form.yzm"
          prefix-icon="el-icon-unlock"
          clearable
          :placeholder="t('login.smsPlaceholder')"
        >
        </el-input>
        <el-button @click="getYzm" :disabled="disabled"
          >{{ t("login.smsGet")
          }}<span v-if="disabled"> ({{ time }})</span></el-button
        >
      </div>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        style="width: 100%"
        :loading="islogin"
        round
        @click="login"
        >{{ t("login.signIn") }}
      </el-button>
    </el-form-item>
    <div class="login-reg">
      {{ t("login.noAccount") }}
      <router-link to="/user_register">{{
        t("login.createAccount")
      }}</router-link>
    </div>
  </el-form>
</template>

<script>
export default {
  name: "phoneForm",
};
</script>
<script setup>
import { useI18n } from "vue-i18n";
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";

const { t } = useI18n();

let disabled = ref(false);
let islogin = ref(false);
let time = ref(0);

let form = reactive({
  phone: "",
  yzm: "",
});

let rules = reactive({
  phone: [{ required: true, message: t("login.mobileError") }],
  yzm: [{ required: true, message: t("login.smsError") }],
});

const loginForm = ref(null);

// 获取验证码
const getYzm = async () => {
  var validate = await loginForm.value.validateField("phone").catch(() => {});
  if (!validate) {
    return false;
  }

  ElMessage.success(this.t("login.smsSent"));
  disabled.value = true;
  time.value = 60;
  var t = setInterval(() => {
    time.value -= 1;
    if (time.value < 1) {
      clearInterval(t);
      disabled.value = false;
      time.value = 0;
    }
  }, 1000);
};

let login = async () => {
  var validate = await loginForm.value.validate().catch(() => {});
  if (!validate) {
    return false;
  }
};
</script>

<style lang="scss" scoped></style>
